package edu.xidian.forum.controller;

import edu.xidian.forum.common.Result;
import edu.xidian.forum.dto.TipDto;
import edu.xidian.forum.entity.Tip;
import edu.xidian.forum.service.TipService;
import edu.xidian.forum.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import static edu.xidian.forum.jwt.JwtUtil.USER_NAME;

@RestController
@RequestMapping("/tip")
public class TipController {
    @Resource
    private TipService tipService;

    @Resource
    private UserService userService;

    @GetMapping("/random")
    public Result<Tip> getRandomTip() {
        return Result.success(tipService.getRandomTip());
    }

    @PostMapping("/add")
    public Result<Tip> addTip(@RequestHeader(value = USER_NAME) String username, @RequestBody TipDto tipDto) {
        if (!userService.isAdmin(username)) {
            return Result.failed("Admin No valid!");
        }
        return tipService.insertTip(tipDto);
    }

    @PostMapping("/update")
    public Result updateTip(@RequestHeader(value = USER_NAME) String username, @RequestBody TipDto tipDto) {
        if (!userService.isAdmin(username)) {
            return Result.failed("Admin No valid!");
        }
        return tipService.updateTip(tipDto);
    }

    @PostMapping("/delete")
    public Result deleteTip(@RequestHeader(value = USER_NAME) String username, @RequestBody TipDto tipDto) {
        if (!userService.isAdmin(username)) {
            return Result.failed("Admin No valid!");
        }
        return tipService.deleteTip(tipDto);
    }
}
